/**
 * 用户角色关联控制器
 * 作者：GodMainCode
 * 创建时间：2024-01-17
 * 修改时间：2024-01-17
 * 修改人：GodMainCode
 */

import { 
  Controller, 
  Post, 
  Body, 
  Param, 
  Delete,
  HttpCode,
  HttpStatus,
  UseGuards
} from '@nestjs/common';
import { 
  ApiTags, 
  ApiOperation, 
  ApiResponse,
  ApiParam,
  ApiBody,
  ApiProperty
} from '@nestjs/swagger';
import { UserRoleService } from './user-role.service';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { RequirePermissions } from '../auth/decorators/permissions.decorator';
import { IsArray, IsInt } from 'class-validator';

class AssignRolesDto {
  @ApiProperty({ description: '角色ID列表', type: [Number] })
  @IsArray()
  @IsInt({ each: true })
  roleIds: number[];
}

@ApiTags('用户角色管理')
@UseGuards(JwtAuthGuard)
@Controller('user-role')
export class UserRoleController {
  constructor(private readonly userRoleService: UserRoleService) {}

  @Post(':userId/roles')
  @HttpCode(HttpStatus.OK)
  @RequirePermissions('user:assignRole')
  @ApiOperation({ summary: '为用户分配角色' })
  @ApiParam({ name: 'userId', description: '用户ID' })
  @ApiBody({ type: AssignRolesDto })
  @ApiResponse({ 
    status: HttpStatus.OK, 
    description: '角色分配成功' 
  })
  async assignRoles(
    @Param('userId') userId: string,
    @Body() assignRolesDto: AssignRolesDto,
  ) {
    await this.userRoleService.assignRoles(+userId, assignRolesDto.roleIds);
    return { message: '角色分配成功' };
  }

  @Delete(':userId/roles')
  @HttpCode(HttpStatus.OK)
  @RequirePermissions('user:removeRole')
  @ApiOperation({ summary: '移除用户的角色' })
  @ApiParam({ name: 'userId', description: '用户ID' })
  @ApiBody({ type: AssignRolesDto })
  @ApiResponse({ 
    status: HttpStatus.OK, 
    description: '角色移除成功' 
  })
  async removeRoles(
    @Param('userId') userId: string,
    @Body() assignRolesDto: AssignRolesDto,
  ) {
    await this.userRoleService.removeRoles(+userId, assignRolesDto.roleIds);
    return { message: '角色移除成功' };
  }
} 